package cn.wj.school.server.net.utils;


import cn.wj.school.server.net.context.DispatchTask;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Author: yueding
 * @Description:
 * @Date: Created in 11:39 2019/3/20
 * @Modified By: yueding Copyright(c) cai-inc.com
 */
public class ThreadPoolUtils {

    private static final int CORE_SIZE = Runtime.getRuntime().availableProcessors();

    private static ExecutorService[] executors = new ExecutorService[CORE_SIZE];

    static {
        for (int i = 0; i < executors.length; i++) {
            ExecutorService executor = Executors.newSingleThreadExecutor(new NamedThreadFactory("message-dispatcher"));
            executors[i] = executor;
        }
    }

    public static void addTask(DispatchTask task) {
        // 根据分发id求模映射
        int index = task.getDispatchKey() % executors.length;
        executors[index].submit(task);
    }
}
